﻿#include "MutatedManworm.h"
#include "../../../Shared/Data/Stat.h"
#include "../../MirEnvir/Envir.h"
#include "../MapObject.h"

using namespace Server::MirDatabase;
using namespace Server::MirEnvir;
namespace S = ServerPackets;

namespace Server::MirObjects::Monsters
{

    MutatedManworm::MutatedManworm(MonsterInfo *info) : CrazyManworm(info)
    {
    }

    int MutatedManworm::Attacked(PlayerObject *attacker, int damage, DefenceType type, bool damageWeapon)
    {
        int attackerDamage = CrazyManworm::Attacked(attacker, damage, type, damageWeapon);

        int ownDamage = GetAttackPower(Stats[Stat::MinDC], Stats[Stat::MaxDC]);

        if (attackerDamage > ownDamage && getEnvir()->Random->Next(2) == 0)
        {
            TeleportToWeakerTarget();
        }

        return attackerDamage;
    }

    int MutatedManworm::Attacked(MonsterObject *attacker, int damage, DefenceType type)
    {
        int attackerDamage = CrazyManworm::Attacked(attacker, damage, type);

        int ownDamage = GetAttackPower(Stats[Stat::MinDC], Stats[Stat::MaxDC]);

        if (attackerDamage > ownDamage && getEnvir()->Random->Next(2) == 0)
        {
            TeleportToWeakerTarget();
        }

        return attackerDamage;
    }

    void MutatedManworm::TeleportToWeakerTarget()
    {
        std::vector<MapObject*> targets = FindAllTargets(AttackRange, getCurrentLocation());

        if (targets.size() < 2)
        {
            return;
        }

        for (int i = 0; i < targets.size(); i++)
        {
            if (targets[i]->Stats[Stat::MinDC] > getTarget()->Stats[Stat::MinDC])
            {
                continue;
            }

            setCurrentLocation(targets[i]->getCurrentLocation());
            setTarget(targets[i]);

            TeleportRandom(5, 2, getCurrentMap());
            break;
        }
    }

    bool MutatedManworm::TeleportRandom(int attempts, int distance, Map *temp)
    {
        for (int i = 0; i < attempts; i++)
        {
            Point *location;

            if (distance <= 0)
            {
                location = new Point(getEnvir()->Random->Next(getCurrentMap()->Width), getEnvir()->Random->Next(getCurrentMap()->Height));
            }
            else
            {
                location = new Point(getCurrentLocation()->X + getEnvir()->Random->Next(-distance, distance + 1), getCurrentLocation()->Y + getEnvir()->Random->Next(-distance, distance + 1));
            }

            if (Teleport(getCurrentMap(), location, true, Info->Effect))
            {
//C# TO C++ CONVERTER TODO TASK: A 'delete location' statement was not added since location was passed to a method or constructor. Handle memory management manually.
                return true;
            }

//C# TO C++ CONVERTER TODO TASK: A 'delete location' statement was not added since location was passed to a method or constructor. Handle memory management manually.
        }

        return false;
    }
}
